import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Table } from 'antd';
import moment from 'moment';

import cols from './closedPositionsColumns';

const columns = cols.map((item) => {
  item.sorter = true;
  return item;
});

const mapStateToProps = state => ({
  list: state.retailClosedPositions.list,
  page: state.retailClosedPositions.page,
  selected: state.retailClosedPositions.selected,
  selectedTrader: state.retailFeatureList.selectedTrader,
});

const mapDispatchToProps = {
  getClosedPositions: query => ({
    type: 'retailClosedPositions/getClosedPositions',
    payload: query || {},
  }),
};

@connect(mapStateToProps, mapDispatchToProps)
export default class ClosedPositionsList extends Component {
  static propTypes = {
    list: PropTypes.array.isRequired,
    page: PropTypes.object,
  }
  state = {
    pagination: { currentpage: 1, pagesize: 10 },
  }
  componentDidMount() {
    if(this.props.selectedTrader!=null){
      this.getData(this.props);
    }
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps !== this.props && nextProps.selectedTrader!=this.props.selectedTrader) {
      this.getData(nextProps);
    }
  }
  getData({ getClosedPositions, selectedTrader } , other={}) {
      const { trader } = selectedTrader;
      const { pagination } = this.state;
      getClosedPositions({ trader, ...pagination , ...other });
  }
  handleTableChange = (pagination, filters, sorter) => {
    const pager = { ...this.state.pagination };
    pager.currentpage = pagination.current;

    const query = {
      ...pager,
      trader: this.props.selectedTrader.trader,
    };

    if (sorter.columnKey) {
      query.sortField = sorter.columnKey;
      query.sortOrder = sorter.order;
    }

    this.setState({
      pagination: pager,
    }, ()=>{
      this.getData(this.props, query);
    });
  }
  render() {
    const { list, page: { totalnum } } = this.props;
    const { pagination: { currentpage, pagesize } } = this.state;
    const pager = { current: currentpage, pageSize: pagesize, total: totalnum };
    return (
      <div>
        <Table
          size="small"
          dataSource={list}
          columns={columns}
          pagination={pager}
          onChange={this.handleTableChange}
        />
      </div>
    );
  }
}

